import time
import json

import webapp2
from webapp2_extras.i18n import gettext as _

from google.appengine.api import users
from apnetmodels.basicmodels import immeuble, supplier, person, company
from common import functions
from wtforms.ext.appengine.db import model_form
from wtforms.ext.appengine.fields import ReferencePropertyField
from wtforms.fields import TextField

from BaseHandler import BaseHandler

class Suppliers(BaseHandler):
    def __init__(self, *args, **kwargs):
        super(Suppliers, self).__init__(*args, **kwargs)
        self.au = functions.GetAPNETUser()
        if not self.au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        self.fields = {
                       'syndic': _('Syndic'), 'contact': _('Supplier'), 'type_of_work': _('Type of work'),
                       'contact_person': _('Contact person'), 'name': _('Name'), 'tel': _('Tel'), 'fax': _('Fax'),
                       'address': _('Address'), 'email': _('Email'), 'first_name': _('First name'), 
                       'last_name': _('Last name'), 'default_phone': _('Phone number'), 
                       'default_email': _('Email')
                       }
    
    def get(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)

    def post(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)
    
    def op_add(self, *args, **kwargs):
        kwargs['who'] = 'person'
        self.op_addpc(self, *args, **kwargs)
    def op_add_company(self, *args, **kwargs):
        kwargs['who'] = 'company'
        self.op_addpc(self, *args, **kwargs)
    
    def op_list(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        template_values = {
                           'title': _('Suppliers. %s' % imm.name),
                           'header': _('%s. Suppliers.' % imm.name),
                           'app_user': self.au,
                           'immeuble': imm,
                           'lurl': users.create_logout_url('/'),
                           'section': 'vie',
                           'leftmenu': 'suppliers',
                           'fields': self.fields
                           }

        template = self.jinja2.get_template('templates/suppliers_list.html')
        self.response.out.write(template.render(template_values))
    
    def op_list_json(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        supls = supplier.all().filter('syndic =', imm.syndic).run()
        sl = []
        for s in supls:
            if s.contact.class_name() == 'person':
                sl.append([unicode(s.contact.first_name) + ' ' + unicode(s.contact.last_name), unicode(s.type_of_work), unicode(s.contact.default_phone), '', unicode(s.contact.address), unicode(s.contact_person), s.contact.default_email, str(s.key().id())])
            else:
                sl.append([unicode(s.contact.name), unicode(s.type_of_work), unicode(s.contact.default_phone), unicode(s.contact.fax_number), unicode(s.contact.address), unicode(s.contact_person), s.contact.default_email, str(s.key().id())])
        ret = {}
        ret['aaData'] = sl
        self.response.out.write(json.dumps(ret))
    
    def op_list_names_json(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        supls = supplier.all().filter('syndic =', imm.syndic).run()
        sl = []
        for s in supls:
            if s.contact.class_name() == 'person':
                sl.append(str(s.contact.first_name) + ' ' + str(s.contact.last_name) + ' (' + str(s.type_of_work) + ')')
            else:
                sl.append(str(s.contact.name) + ' (' + str(s.type_of_work) + ')')
        self.response.out.write(json.dumps(sl))
    
    def op_addpc(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        who = kwargs.get('who', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        works_list = []
        for w in imm.syndic.type_of_work_set.order('label').run():
            works_list.append(w)
        
        ok_message = ''
        if who == 'person':
            PersonForm = model_form(person, only=['first_name','last_name','default_phone','default_email'])
            setattr(PersonForm, 'type_of_work', ReferencePropertyField(label='Type of work'))
        else:
            CompanyForm = model_form(company, only=['name','default_phone','default_email'])
            setattr(CompanyForm, 'type_of_work', ReferencePropertyField(label='Type of work'))
            setattr(CompanyForm, 'contact_person', TextField(label='Contact'))
            
        if self.request.method == 'GET':
            if who == 'person':
                form = PersonForm()
            else:
                form = CompanyForm()
            form['type_of_work'].query = imm.syndic.type_of_work_set.order('label')
                
        if self.request.method == 'POST':
            if who == 'person':
                form = PersonForm(self.request.POST)
            else:
                form = CompanyForm(self.request.POST)
            form['type_of_work'].query = imm.syndic.type_of_work_set.order('label')
            if form.validate():
                c_person = None 
                work = form['type_of_work'].data 
                if who == 'person':
                    f_name = form['first_name'].data.strip()
                    l_name = form['last_name'].data.strip()
                    phone = form['default_phone'].data
                    email = form['default_email'].data
                    cnt = imm.syndic.syndic_contacts.filter('first_name = ', f_name).filter('last_name = ', l_name).filter('default_phone = ', phone).filter('default_email = ',email).get()
                    if not cnt:
                        cnt = person(syndic = imm.syndic,
                                     first_name = f_name,
                                     last_name = l_name,
                                     default_phone = phone,
                                     default_email = email,
                                     lastchange_by = self.au)
                        cnt.put()
                        while not cnt.is_saved():
                            time.sleep(2)
                else:
                    c_person = form['contact_person'].data
                    c_name = form['name'].data.strip()
                    phone = form['default_phone'].data
                    email = form['default_email'].data
                    cnt = imm.syndic.syndic_contacts.filter('name = ', c_name).filter('default_phone = ', phone).filter('default_email = ',email).get()
                    if not cnt:
                        cnt = company(syndic = imm.syndic,
                                     name = c_name,
                                     default_phone = phone,
                                     default_email = email,
                                     lastchange_by = self.au)
                        cnt.put()
                        while not cnt.is_saved():
                            time.sleep(2)
                    
                s = imm.syndic.supplier_set.filter('contact =', cnt).filter('type_of_work =', work).get()
                if s:
                    ok_message = _('Supplier already registered.')
                else:
                    new_supplier = supplier( syndic = imm.syndic,
                                             contact = cnt,
                                             type_of_work = work,
                                             contact_person = c_person)
                    new_supplier.put()
                    
                    while not new_supplier.is_saved():
                        time.sleep(2)
                    ok_message = _('New Supplier added.')
        template_values = {
                           'form': form,
                           'ok_message': ok_message,
                           'fields': self.fields
                           }
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
    
    
    def op_edit(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        s_id = kwargs.get('s_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return    
        sup_obj = supplier.get_by_id(int(s_id))
        if not sup_obj: 
            self.redirect(webapp2.uri_for('mainpage'))
            return    
            
        ok_message = ''
        SupplierForm = model_form(supplier, exclude=['syndic'])
        
        if self.request.method == 'GET':
            form = SupplierForm(obj = sup_obj)
            form['contact'].query = imm.syndic.syndic_contacts
            form['type_of_work'].query = imm.syndic.type_of_work_set
            
        if self.request.method == 'POST':
            form = SupplierForm(self.request.POST)
            form['contact'].query = imm.syndic.syndic_contacts
            form['type_of_work'].query = imm.syndic.type_of_work_set
            
            if form.validate():
                form.populate_obj(sup_obj)
                sup_obj.put()
                
                ok_message = _('Supplier was updated.')
        
        template_values = {'form': form, 'ok_message': ok_message, 'fields': self.fields}
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
